package com.graphqljava.demo.gql.gql.fetchers;

import com.google.common.collect.ImmutableMap;
import graphql.schema.DataFetcher;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * com.graphqljava.demo.gql
 *
 * @author Oscar.Chen
 * @date 6/15/2020 12:36 PM
 */
@Component
public class InMemoryGraphQLDataFetchers {

    private static List<Map<String, String>> posts = Arrays.asList(
        ImmutableMap.of("id", "pid-1",
            "title", "GraphQL基础概念",
            "url", "b.tv/404",
            "description", "233",
            "userId", "uid-1"),
        ImmutableMap.of("id", "pid-2",
            "title", "GraphQL Java 入门",
            "url", "b.tv/404",
            "description", "2333",
            "userId", "uid-1"),
        ImmutableMap.of("id", "pid-3",
            "title", "GraphQL 放弃",
            "url", "b.tv/404",
            "description", "23333333",
            "userId", "uid-1")
    );

    private static List<Map<String, String>> users = Arrays.asList(
        ImmutableMap.of("id", "uid-1",
            "firstName", "Oscar",
            "lastName", "Chen"),
        ImmutableMap.of("id", "uid-2",
            "firstName", "Three",
            "lastName", "Zhang")
    );

    public DataFetcher getPostByIdDataFetcher() {
        return dataFetchingEnvironment -> {
            String postId = dataFetchingEnvironment.getArgument("id");
            return posts
                .stream()
                .filter(e -> e.get("id").equals(postId))
                .findFirst()
                .orElse(null);
        };
    }

    public DataFetcher getUserByIdDataFetcher() {
        return dataFetchingEnvironment -> {
            String userId = dataFetchingEnvironment.getArgument("id");
            return users
                .stream()
                .filter(e -> e.get("id").equals(userId))
                .findFirst()
                .orElse(null);
        };
    }

    public DataFetcher getUserDataFetcher() {
        return dataFetchingEnvironment -> {
            Map<String, String> user = dataFetchingEnvironment.getSource();
            String userId = user.get("userId");

            return users
                .stream()
                .filter(e -> e.get("id").equals(userId))
                .findFirst()
                .orElse(null);
        };
    }

    public DataFetcher getPostDataFetcher() {
        return dataFetchingEnvironment -> {
            Map<String, String> source = dataFetchingEnvironment.getSource();
            String userId = source.get("id");

            Object[] items = posts
                .stream()
                .filter(e -> e.get("userId").equals(userId))
                .toArray();
            if (items.length > 0) {
                return items;
            } else {
                return null;
            }
        };
    }

}
